package com.java.simple.study.jvm.memstruct.methodarea;

import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.Opcodes;

/**
 * @author zhoujunlin
 * @date 2021/12/12
 * @desc 演示元空间内存溢出
 * ClassLoader类：用来加载类的二进制字节码
 * 不设置上限 count= 10000
 * jdk8方法区位于操作系统内存 不容易溢出 手动设置大小 -XX:MetaspaceSize=10m -XX:MaxMetaspaceSize=10m
 * count = 8531  java.lang.OutOfMemoryError: Metaspace
 **/
public class OOMTest extends ClassLoader {

    public static void main(String[] args) {
        int count = 0;
        OOMTest test = new OOMTest();
        try {
            for (int i = 0; i < 10000; i++, count++) {
                // 用于生成类的二进制字节码
                ClassWriter classWriter = new ClassWriter(0);
                //参数分别为：JDK版本，访问控制符，类名，包名，父类，实现接口
                classWriter.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, "Class" + i, null, "java/lang/Object", null);
                byte[] bytes = classWriter.toByteArray();
                // 执行类加载  返回Class对象
                test.defineClass("Class" + i, bytes, 0, bytes.length);
            }
        } finally {
            System.out.println(count);
        }
    }
}